<template>
  <div id="mapContainer">
    <div id="amap" ref="amap"></div>
  </div>
</template>

<script>
import Loading from '@/components/loading';
const MARKER_MOVE_SPEED = 75;
var moment = require('moment');
moment.locale('zh-cn');
export default {
  name: 'incity-map',
  data() {
    return {
      instance: null,
      geolocation: null,
      picker: null,
      dingweiMarkder: null,
      dingweiIcon: new AMap.Icon({
        size: new AMap.Size(36, 46),
        image: require('@/assets/imgs/dw_icon.png'),
        imageSize: new AMap.Size(18, 23)
      }),
      currentRoutes: null,
      driveCar: null,
      drivePath: null,
      driveCarInfo: {
        timeStr: '',
        mileStr: '',
        milePreStr: '距终点'
      },
      driveDistance: 0,
      orderSeqMarkers: [],
      countdownInterval: null,
      countdownMarker: null,
      travellingTipBusy: false,
      adsorptionFenceInfo: [],
      adsorptionFence: null,
      adsorptionMarkers: [],
      adsorptionPoint: null,
      adsorptionPanFlag: false,
      adsorptionStationId: undefined
    };
  },
  props: {
    center: {
      type: Array,
      default: () => {
        return [116.397428, 39.90923];
      }
    },
    zoom: {
      type: Number,
      default: 17
    },
    noAutoZoom: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    Loading.show();
    let c = this.center;
    let z = this.zoom;
    this.instance = new AMap.Map(this.$refs.amap, {
      zoom: z, // 级别
      center: c, // 中心点坐标
      mapStyle: 'amap://styles/b7bb350207a4d6e98610556cbaa8d41b'
    });
    this.instance.on('complete', evt => {
      console.log('市内用车地图加载完成');
      this.$emit('complete', this.instance);
      Loading.hide();
      if (process.env.NODE_ENV === 'development') {
        AMap.plugin(['AMap.ToolBar'], () => {
          let toolbar = new AMap.ToolBar({
            position: 'RT'
          });
          this.instance.addControl(toolbar);
        });
      }
    });
    this.instance.on('dragstart', evt => {
      this.$emit('dragstart');
    });
  },
  methods: {
    initPositionPicker() {
      if (this.picker) {
        return;
      }
      // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
      AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
        this.picker = new PositionPicker({
          mode: 'dragMap', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: this.instance, // 依赖地图对象
          iconStyle: {
            // 自定义外观
            url: require('@/assets/imgs/sc_datouzhen.png'), // 图片地址
            size: [25, 36], // 要显示的点大小，将缩放图片
            ancher: [12.5, 36] // 锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
          }
        });
        this.picker.on('success', this.onPickerSelect);
        this.picker.start();
      });
    },
    stopPositionPicker() {
      if (this.picker) {
        this.picker.stop();
        this.picker.off('sucess', this.onPickerSelect);
        this.picker = null;
      }
    },
    onPickerSelect(positionResult) {
      let result = {
        coordinate: [],
        stationName: '',
        position: '',
        adcode: '',
        city: ''
      };
      result.coordinate = [positionResult.position.lng, positionResult.position.lat];
      if (positionResult.regeocode.pois.length > 0) {
        result.stationName = positionResult.regeocode.pois[0].name;
      } else {
        result.stationName = positionResult.regeocode.formattedAddress;
      }
      if (positionResult.regeocode.addressComponent) {
        result.adcode = positionResult.regeocode.addressComponent.adcode;
        result.city = positionResult.regeocode.addressComponent.province;
      }
      result.position = positionResult.address;
      if (!this.adsorptionPanFlag) {
        this.$emit('select', result);
      } else {
        this.adsorptionPanFlag = false;
        result.adsorption = true;
        result.stationName = this.adsorptionPoint.shortName;
        result.position = this.adsorptionPoint.longName;
        result.stationId = this.adsorptionStationId;
        this.$emit('select', result);
      }
    },
    initCenter(center) {
      if (this.instance) {
        this.instance.setCenter(center);
        this.instance.setZoom(17);
        if (this.dingweiMarkder) {
          this.instance.remove(this.dingweiMarkder);
          this.dingweiMarkder = null;
          this.dingweiMarkder = new AMap.Marker({
            position: center,
            icon: this.dingweiIcon,
            offset: new AMap.Pixel(-8, -12)
          });
          this.instance.add(this.dingweiMarkder);
        } else {
          this.dingweiMarkder = new AMap.Marker({
            position: center,
            icon: this.dingweiIcon,
            offset: new AMap.Pixel(-8, -12)
          });
          this.instance.add(this.dingweiMarkder);
        }
      }
    },
    addDingweiMarker(lnglat) {
      if (this.dingweiMarkder) {
        this.instance.remove(this.dingweiMarkder);
        this.dingweiMarkder = null;
        this.dingweiMarkder = new AMap.Marker({
          position: lnglat,
          icon: this.dingweiIcon,
          offset: new AMap.Pixel(-8, -12)
        });
        this.instance.add(this.dingweiMarkder);
      } else {
        this.dingweiMarkder = new AMap.Marker({
          position: lnglat,
          icon: this.dingweiIcon,
          offset: new AMap.Pixel(-8, -12)
        });
        this.instance.add(this.dingweiMarkder);
      }
    },
    setCenter(center) {
      if (this.instance) {
        this.instance.setCenter(center);
      }
    },
    setCenterAndFitview(center) {
      if (this.instance) {
        this.instance.setCenter(center);
        this.instance.setZoom(16);
      }
    },
    initFences(fences) {
      if (fences.length > 1) {
        this.polygon = new AMap.Polygon({
          // 绘制围栏
          map: this.instance,
          path: fences,
          strokeColor: '#FF6917',
          strokeOpacity: 1,
          strokeWeight: 4,
          fillColor: '#FF6917',
          fillOpacity: 0.1
        });
        this.instance.add(this.polygon);
      }
    },
    isContain(coordinate) {
      if (this.polygon) {
        return this.polygon.contains(coordinate);
      }
      return false;
    },
    removeFences() {
      if (this.polygon) {
        this.instance.remove(this.polygon);
        this.polygon = null;
      }
    },
    showStartEndPosition(start, end, path = false, hasTip = false) {
      this.addStartMarker(start.coordinate, start.stationName);
      this.addEndMarker(end.coordinate, end.stationName);
      if (path) {
        this.createDrivingRoute(start.coordinate, end.coordinate).then(res => {
          if (hasTip) {
            let dis = res.distance / 1000;
            this.createTextTip(end.coordinate, dis.toFixed(1), '3');
          }
          this.updateDrivedPath();
        });
      }
      this.instance.setFitView();
    },
    addStartMarker(lnglat, name = '') {
      // 添加一个起点marker对象
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: require('@/assets/imgs/snyc_shangche_icon.png'),
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-10, -24),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-location-name">' + name + '</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(0, 15)
        });
        this.instance.add(textMarker);
      }
    },
    addEndMarker(lnglat, name = '') {
      // 添加一个终点marker对象
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: require('@/assets/imgs/snyc_xiache_icon.png'),
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-10, -24),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-location-name">' + name + '</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(0, 15)
        });
        this.instance.add(textMarker);
      }
    },
    addPartnerStartMarker(lnglat) {
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(24, 24), // 图标尺寸
          image: require('@/assets/imgs/txck_icon.png'),
          imageSize: new AMap.Size(16, 16) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-8, -8),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-partner-name">同行乘客</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(35, 8)
        });
        this.instance.add(textMarker);
      }
    },
    addPartnerEndMarker(lnglat) {
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(24, 24), // 图标尺寸
          image: require('@/assets/imgs/txck_zd_icon.png'),
          imageSize: new AMap.Size(16, 16) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-8, -8),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-partner-name">同行乘客</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(38, 8)
        });
        this.instance.add(textMarker);
      }
    },
    updateDriveCar(position) {
      if (this.driveCar) {
        this.driveCar.moveTo(position, MARKER_MOVE_SPEED);
      } else {
        this.driveCar = new AMap.Marker({
          map: this.instance,
          position: position,
          offset: new AMap.Pixel(-18, -9),
          angle: -90,
          autoRotation: true,
          icon: new AMap.Icon({
            size: new AMap.Size(72, 36), // 图标尺寸
            image: process.env.BASE_URL + 'static/imgs/car@2x.png',
            imageSize: new AMap.Size(36, 18) // 根据所设置的大小拉伸或压缩图片
          })
        });
      }
      if (this.driveCarText) {
        this.driveCarText.moveTo(position, MARKER_MOVE_SPEED);
      }
    },
    createTextTip(position, text) {
      this.closeTextTip();
      let str = '<div class="map-shareorder-infowindow">' + text + '</div>';
      this.driveCarText = new AMap.Text({
        map: this.instance,
        bubble: false,
        text: str,
        position: position,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        clickable: false,
        offset: new AMap.Pixel(0, -55)
      });
    },
    addIncityTravellingTip(position, distance, time) {
      this.closeTextTip();
      let distanceStr = (distance / 1000).toFixed(2);
      let minStr = Math.floor(parseInt(time) / 60);
      let timeStr = minStr + '分钟';
      // 行程中提示文字
      let str =
        '<div class="map-shareorder-infowindow">距终点<span style="color:#FF6917">' +
        distanceStr +
        '公里</span><br>预计行驶<span style="color:#FF6917">' +
        timeStr +
        '</span></div>';
      this.driveCarText = new AMap.Text({
        map: this.instance,
        bubble: false,
        text: str,
        position: position,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '50px'
        },
        clickable: false,
        offset: new AMap.Pixel(0, -40)
      });
    },
    updateIncityTravellingTip(position, pathinfo) {
      if (this.travellingTipBusy) {
        return;
      }
      this.travellingTipBusy = true;
      this.updateIncityOrderWayPathInfo(position, pathinfo).then(result => {
        this.addIncityTravellingTip(position, result.distance, result.time);
        this.travellingTipBusy = false;
      });
    },
    addIncityFinishTip(position, distance) {
      this.closeTextTip();
      // 行程中提示文字
      let str = '<div class="map-shareorder-infowindow">共行驶<span style="color:#FF6917">' + distance + '公里</span>';
      this.driveCarText = new AMap.Text({
        map: this.instance,
        bubble: false,
        text: str,
        position: position,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '50px'
        },
        clickable: false,
        offset: new AMap.Pixel(0, -40)
      });
    },
    closeTextTip() {
      if (this.driveCarText) {
        this.instance.remove(this.driveCarText);
        this.driveCarText = null;
      }
    },
    startCountdown(time, text) {
      this.clearCountdown();
      this.countdownInterval = setInterval(() => {
        time--;
        if (time <= 0) {
          clearInterval(this.countdownInterval);
          this.countdownInterval = null;
        }
        let minStr = Math.floor(time / 60);
        let secStr = time % 60;
        let countStr = minStr + ':' + secStr;
        let str = '<div class="map-shareorder-infowindow"><span style="color:#FF6917">' + countStr + '</span>' + text + '</div>';

        if (this.countdownMarker) {
          this.countdownMarker.setText(str);
        }
      }, 1000);
    },
    clearCountdown() {
      if (this.countdownInterval) {
        clearInterval(this.countdownInterval);
        this.countdownInterval = null;
      }
    },
    addCountdownTip(lnglat, text = '', time = '') {
      this.clearCountdown();
      this.removeCountdownTip();
      let now = moment();
      let endTime = moment(parseInt(time));
      let diffTime = endTime.diff(now, 's');
      let countStr = '0:00';
      if (diffTime < 0) {
        let countStr = '0:00';
      } else {
        let minStr = Math.floor(diffTime / 60);
        let secStr = diffTime % 60;
        countStr = minStr + ':' + secStr;
        this.startCountdown(diffTime, text);
      }
      let str = '<div class="map-shareorder-infowindow"><span style="color:#FF6917">' + countStr + '</span>' + text + '</div>';
      this.countdownMarker = new AMap.Text({
        map: this.instance,
        bubble: false,
        text: str,
        position: lnglat,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        clickable: false,
        offset: new AMap.Pixel(0, -25)
      });
      // let count = 0;
      // let counter = setInterval(() => {
      //     count++;
      //     console.log(count);
      //     if (count >= time) {
      //         clearInterval(counter);
      //         console.log('清除计时器');
      //     }
      // }, 1000);
    },
    removeCountdownTip() {
      if (this.countdownMarker) {
        this.instance.remove(this.countdownMarker);
        this.countdownMarker = null;
      }
    },
    createPathNavigator(start, dest) {
      return new Promise((resolve, reject) => {
        this.createDrivingRoute(start, dest)
          .then(result => {
            console.log(result);
            let timeLeftMin = result.time / 60;
            let timeLeftStr = timeLeftMin.toFixed(0) + '分钟';
            let mileLeftMeter = result.distance / 1000;
            let mileLeftStr = mileLeftMeter.toFixed(1) + '公里';
            this.driveCarInfo = {
              timeStr: timeLeftStr,
              mileStr: mileLeftStr
            };
            this.updateDrivePath();
            resolve();
          })
          .catch(reason => {
            reject(reason);
          });
      });
    },
    createDrivingRoute(start, dest, opt) {
      return new Promise((resolve, reject) => {
        if (this.instance) {
          AMap.plugin('AMap.Driving', () => {
            let result = null;
            let driving = new AMap.Driving({
              // map: this.mapInstance,
              hideMarkers: true,
              autoFitView: false,
              showTraffic: false,
              isOutline: false,
              policy: AMap.DrivingPolicy.REAL_TRAFFIC
            });
            let wayPoints = {
              waypoints: opt
            };
            driving.search(start, dest, wayPoints, (status, data) => {
              if (data.routes) {
                if (data.routes.length > 0) {
                  this.currentRoutes = [];
                  result = data.routes[0];
                  result.steps.forEach(item => {
                    item.path.forEach(item => {
                      this.currentRoutes.push(item);
                    });
                  });
                  resolve(result);
                } else {
                  reject(new Error('线路规划失败' + data));
                }
              } else {
                reject(new Error('线路规划失败' + data));
              }
            });
          });
        } else {
          reject(new Error('地图还没有初始化，无法使用实时导航功能'));
        }
      });
    },
    showIncityOrderWayPath(driverCoord, pathinfo) {
      return new Promise((resolve, reject) => {
        Loading.show();
        let pathCoords = [];
        if (pathinfo && pathinfo.length > 0) {
          pathinfo.forEach((item, index) => {
            this.drawPointsByOrderSeq(item);
            pathCoords.push(item.lnglat);
          });
          let endInfo = pathCoords.pop();
          this.createDrivingRoute(driverCoord, endInfo, pathCoords).then(result => {
            Loading.hide();
            this.updateDrivePath();
            resolve(result);
          });
        } else {
          Loading.hide();
          reject(new Error('线路规划信息'));
        }
      });
    },
    updateIncityOrderWayPathInfo(driverCoord, pathinfo) {
      return new Promise((resolve, reject) => {
        let pathCoords = [];
        if (pathinfo && pathinfo.length > 0) {
          pathinfo.forEach((item, index) => {
            this.drawPointsByOrderSeq(item);
            pathCoords.push(item.lnglat);
          });
          let endInfo = pathCoords.pop();
          this.createDrivingRoute(driverCoord, endInfo, pathCoords).then(result => {
            resolve(result);
          });
        } else {
          Loading.hide();
          reject(new Error('线路规划信息'));
        }
      });
    },
    drawPointsByOrderSeq(item) {
      if (item.pointType === '1') {
        // 绘制我的起点
        this.addStartMarker(item.lnglat, item.lnglatText);
      } else if (item.pointType === '2') {
        // 绘制我的终点
        this.addEndMarker(item.lnglat, item.lnglatText);
      } else if (item.pointType === '3') {
        // 绘制拼友的起点
        this.addPartnerStartMarker(item.lnglat);
      } else if (item.pointType === '4') {
        // 绘制拼友的终点
        this.addPartnerEndMarker(item.lnglat);
      }
    },
    updateDrivePath() {
      if (this.drivePath) {
        this.drivePath.setPath(this.currentRoutes);
      } else {
        this.drivePath = new AMap.Polyline({
          map: this.instance,
          path: this.currentRoutes,
          strokeWeight: 5,
          strokeColor: '#0AA436'
        });
      }
    },
    updateDrivedPath() {
      let color = '#BFBFBF';
      if (this.drivePath) {
        this.drivePath.setPath(this.currentRoutes);
      } else {
        this.drivePath = new AMap.Polyline({
          map: this.instance,
          path: this.currentRoutes,
          strokeWeight: 5,
          strokeColor: color
        });
      }
    },
    removePathNavigator() {
      if (this.driveCar) {
        this.driveCar.stopMove();
        this.instance.remove(this.driveCar);
        this.driveCar = null;
      }
      if (this.drivePath) {
        this.instance.remove(this.drivePath);
        this.drivePath = null;
      }
    },
    clearMap() {
      if (this.instance) {
        this.instance.clearMap();
        this.removePathNavigator();
        this.clearCountdown();
      }
    },
    setFitView() {
      if (this.instance) {
        this.instance.setFitView();
      }
    },
    createAdsorptionFence(fences) {
      this.clearAdsorptionFence();
      if (typeof fences === 'string') {
        this.adsorptionFenceInfo = fences.split(';');
        this.adsorptionFenceInfo.forEach((value, index) => {
          this.adsorptionFenceInfo[index] = value.split(',');
        });
      } else if (fences instanceof Array) {
        this.adsorptionFenceInfo = fences;
      }
      if (this.adsorptionFenceInfo.length > 1) {
        this.adsorptionFence = new AMap.Polygon({
          // 绘制围栏
          map: this.instance,
          path: this.adsorptionFenceInfo,
          strokeColor: '#FF6917',
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: '#FF6917',
          fillOpacity: 0.0
        });
        this.instance.add(this.adsorptionFence);
      }
    },
    createAdsorptionMarkers(coords, stationId = undefined) {
      this.clearAdsorptionMarkers();
      this.adsorptionStationId = stationId;
      if (coords instanceof Array) {
        coords.forEach((value, index) => {
          const coord = value.lnglat.split(',');
          this.createAdsorptionMarker(coord, value.shortName);
          if (value.isTarget === '1') {
            this.adsorptionPoint = value;
            this.instance.panTo(coord);
            this.adsorptionPanFlag = true;
          }
        });
      }
    },
    createAdsorptionMarker(coord, text) {
      const marker = new AMap.CircleMarker({
        map: this.instance,
        center: coord,
        radius: 4,
        fillColor: '#FF6917',
        strokeOpacity: 0
      });
      const markerText = new AMap.Text({
        position: coord,
        map: this.instance,
        text: '<div class="map-location-name">' + text + '</div>',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        offset: new AMap.Pixel(0, 20)
      });
      this.adsorptionMarkers.push({
        marker: marker,
        text: markerText
      });
    },
    clearAdsorptionFence() {
      if (this.adsorptionFence != null) {
        this.instance.remove(this.adsorptionFence);
        this.adsorptionFence = null;
      }
    },
    clearAdsorptionMarkers() {
      if (this.adsorptionMarkers.length > 0) {
        this.adsorptionMarkers.forEach((item, index) => {
          this.instance.remove(item.marker);
          this.instance.remove(item.text);
          this.adsorptionMarkers[index] = undefined;
        });
        this.adsorptionMarkers = [];
      }
    },
    clearAdsorption() {
      this.clearAdsorptionFence();
      this.clearAdsorptionMarkers();
      this.adsorptionPoint = null;
      this.adsorptionPanFlag = false;
    }
  }
};
</script>

<style lang="stylus">
#mapContainer {
  width: 100vw;
  height: 100vh;

  #amap {
    width: 100%;
    height: 100%;
  }
}

.map-shareorder-infowindow {
  position: relative;
  border-radius: 10px;
  padding: 10px 15px;
  box-shadow: 0 2px 6px 0 #999;
  border-radius: 40px;
  background-color: #fff;
  font-size: 24px;
  color: #4A4A4A;
  text-align: center;
  white-space: nowrap;
}

.map-shareorder-infowindow:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 0;
  border: 20px solid transparent;
  border-top-color: #fff;
  border-bottom: 0;
  margin-left: -10px;
  margin-bottom: -10px;
}
</style>